<template>
  <a-card type="inner" title="Article List">
    <template slot="extra">
      <a-button type="primary" icon="file-add" @click="pushRoute({name:'add-article'})">Add</a-button>
    </template>
    <a-table :dataSource="data" :pagination="pagination" :scroll="{ x: 900 }">
      <a-table-column key="title" dataIndex="title" title="Title"/>
      <a-table-column key="date" dataIndex="createdAt" title="Created At">
        <template slot-scope="createdAt">
          <span>{{createdAt | humanize_full}}</span>
        </template>
      </a-table-column>
      <a-table-column key="author" dataIndex="user" title="Author">
        <template slot-scope="user">
          <span>{{user.username}}</span>
        </template>
      </a-table-column>
      <a-table-column key="action" dataIndex="id" title="Action" fixed="right" :width="150">
        <template slot-scope="id">
          <icon-btn name="Edit" icon="edit"
                    @click.native="pushRoute({name: 'edit-article', params: {id}})"></icon-btn>
          <icon-btn name="Delete" icon="delete"
                    @click.native="deleteArticle(id)"></icon-btn>
        </template>
      </a-table-column>
    </a-table>
  </a-card>
</template>

<script>
  import api from '../../api'

  export default {
    name: 'article-list',
    data () {
      return {
        data: [],
        pagination: {
          total: 100,
          pageSize: 10,
          current: 1
        }
      }
    },
    mounted () {
      this.getArticleList()
    },
    methods: {
      getArticleList () {
        let params = {
          limit: this.pagination.pageSize,
          page: this.pagination.current
        }
        api.getArticleList(params).then(resp => {
          this.data = resp.data.data
          this.pagination.total = resp.data.total
        })
      },
      deleteArticle (id) {
        let self = this
        this.$confirm({
          title: "Delete",
          content: "sure to delete?",
          onOk (close) {
            api.deleteArticle(id).then(() => {
              self.$message.success("success")
              self.getArticleList()
              close()
            })
          }
        })
      },
      pushRoute (route) {
        if (route) {
          this.$router.push(route)
        }
      }
    }
  }
</script>

<style>

</style>
